var express = require('express');
var path = require('path');
var logger = require('morgan');
var _ = require("lodash");
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var xmlparser = require('express-xml-bodyparser');
var debug = require("debug")('qywx-runner');
var assert = require('assert');
var jwt = require("jsonwebtoken");
var env = process.env.NODE_ENV;
var config = require(path.join(__dirname, '.', 'config', 'config.' + env + '.json'));
var AuthubFilter = require('aivics-authub-core-filter');
var cors = require('cors');

var app = express();
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(xmlparser({ explicitArray: false }));

app.use("/echo", function(req, res, next){
  return res.status(200).end("I am ok!");
})

function getBearerToken(req){
  var bearer = req.get('authorization');
  debug("Authorization: " + bearer);
  var accessToken;

  if(bearer){
    accessToken = bearer.substring("Bearer".length).trim();
  }


  if(_.isEmpty(accessToken)){
    //Try to get token from url query parameter
    accessToken = req.query.x_bearer;
  }

  if(_.isEmpty(accessToken) && req.cookies){
    accessToken = req.cookies.x_bearer;
  }
  return accessToken;
}

/*
* Before AuthFilter we need setup jwt properly
*/
app.use(function(req, res, next){
  //Try to get the right config
  var accessToken = getBearerToken(req)

  if(!accessToken) return next();

  var decoded = jwt.decode(accessToken);

  if(decoded.corpId && app.locals.accountConfigs){
    var accountConfig = app.locals.accountConfigs[decoded.corpId];
    req.x_account_config = {
      "accessToken": {
        "secret": accountConfig.jwtAccessTokenSecret,
        "algorithm": accountConfig.jwtAccessTokenAlgorithm
      }
    };

    debug("==>correctly setup req.x_account_config property<==")
  }
  return next();
});


var filterOptions = {
  ignores: [
    [ /^\/qywxapi\/auth\/handler.*/ , /^(get|post)$/ig ],
    [ /^\/qywxapi\/auth\/callback.*/ , /^(get|post)$/ig ]
  ]
};

app.use(AuthubFilter().filter(filterOptions, function(identity, cb){
  if(identity.ut === 'admin'){
    return cb(null, false);
  }else if(identity.ut === 'client'){
    //TODO: Should verify if client are permitted to access the requested url!
    return cb(null, false);
  }else{
    return cb(null, false);
  }
}));


module.exports = app;
